import { getStore, setStore } from '@/utils/store'
import users from '@/api/user'
const user = {
  state: {
    //用户信息
    userInfo:
      getStore({
        name: 'userInfo'
      }) || {},
    //token
    satoken:
      getStore({
        name: 'satoken'
      }) || '',
    //是否已经登录
    isLogin:
      getStore({
        name: 'isLogin'
      }) || false
  },
  actions: {
    //token
    setSatoken({ commit }, satoken) {
      commit('SET_TOKEN', satoken)
    },
    //清除登录状态
    clearLogin({ commit }) {
      commit('SET_USER_INFO', {})
      commit('SET_TOKEN', '')
      commit('SET_LONGIN', false)
    },
    //获取用户信息
    async getInfo({ commit }) {
      const res = await users.info()
      console.log(res)
      if (res && res.code == 200) {
        commit('SET_USER_INFO', res.data)
        commit('SET_LONGIN', true)
      }
    }
  },
  mutations: {
    //用户信息
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      setStore({
        name: 'userInfo',
        content: userInfo,
        type: 'session'
      })
    },
    //token
    SET_TOKEN(state, satoken) {
      state.satoken = satoken
      setStore({
        name: 'satoken',
        content: satoken,
        type: 'session'
      })
    },
    //登录状态
    SET_LONGIN(state, login) {
      state.isLogin = login
      setStore({
        name: 'isLogin',
        content: login,
        type: 'session'
      })
    }
  }
}

export default user
